# Maintainer: Maksim Bondarenkov <maksapple2306@gmail.com>

_realname=wasmer
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-lib${_realname}")
pkgver=6.0.1
pkgrel=2
pkgdesc="The leading Wasm Runtime supporting WASIX, WASI and Emscripten (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64')
url="https://github.com/wasmerio/wasmer"
msys2_references=(
  'purl: pkg:cargo/wasmer'
)
license=('spdx:MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-openssl"
             "${MINGW_PACKAGE_PREFIX}-nodejs"
             'git')
source=("git+${url}.git#tag=v${pkgver}"
        "reproducible-builds.patch")
sha256sums=('1be69dd3bae23e86217150adf223360fc458721ea2dc7a5c219257a4b9a3df52'
            '7f08b41e0077a23b16eb2e9410ac953b293d1eeeaf1b83915a596ac437f81125')

prepare() {
  cd "${_realname}"
  rm rust-toolchain

  patch -Np1 -i "../reproducible-builds.patch"

  cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}

build() {
  cd "${_realname}"

  export OPENSSL_NO_VENDOR=1
  export WINAPI_NO_BUNDLED_LIBRARIES=1
  export WASMER_INSTALL_PREFIX=${MINGW_PREFIX}
  make -O ENABLE_SINGLEPASS=1 ENABLE_CRANELIFT=1 ENABLE_LLVM=0
}

# tests require rustup binary
# check() {
#   cd "${_realame}"
#   make test-examples
# }

package_wasmer() {
  install -Dm755 "${_realname}"/target/release/wasmer "${pkgdir}${MINGW_PREFIX}/bin/wasmer"
  install -Dm644 "${_realname}"/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}

package_libwasmer() {
  pkgdesc+=' (C-API)'
  conflicts=("${MINGW_PACKAGE_PREFIX}-libwasmtime")

  install -Dm755 "${_realname}"/target/release/wasmer.dll "${pkgdir}${MINGW_PREFIX}/bin/wasmer.dll"
  install -Dm755 "${_realname}"/target/release/wasmer.dll.a "${pkgdir}${MINGW_PREFIX}/lib/wasmer.dll.a"
  install -Dm755 "${_realname}"/target/release/libwasmer.a "${pkgdir}${MINGW_PREFIX}/lib/libwasmer.a"
  install -vDm644 "${_realname}"/lib/c-api/*.h -t "${pkgdir}${MINGW_PREFIX}/include/"
  "${_realname}"/target/release/wasmer config --pkg-config | install -Dm644 /dev/stdin \
    "${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/wasmer.pc"
  install -Dm644 "${_realname}"/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/lib${_realname}/LICENSE"
}

# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
